<!-- 需求添加、编辑页面 -->
<template>
  <pageHeader :show-back="true" :title="title" :breadCrumb="breadCrumb">
    <template #footer>
      <a-button type="primary" @click="addDemand"> 提交 </a-button>
    </template>
    <div class="title-item">
      <a-space style="margin-left: 40px">
        <div
          style="
            width: 5px;
            height: 23px;
            background-color: rgba(61, 126, 255, 1);
            border: none;
            border-radius: 2px;
          "
        ></div>
        <div>基本信息</div></a-space
      >
    </div>
    <div class="demand-index">
      <a-form
        ref="refForm"
        :model="demand.info"
        autoLabelWidth
        :layout="(layout as Tlayout)"
      >
        <a-row :gutter="16">
          <a-col
            v-for="element in demandForm?.info?.design?.form"
            :key="element.id"
            :span="element.span"
          >
            <FormItem
              :name="element.name"
              :componentType="element.componentType"
              v-model:props="element.props"
              :required="element.required"
              v-model:values="element.values"
            />
          </a-col>
        </a-row>
      </a-form>
    </div>
  </pageHeader>

  <a-modal v-model:visible="visible" @ok="handleOk" @cancel="handleCancel">
    <template #title> 提交需求 </template>
    <div style="display: flex; justify-content: center; align-items: center">
      <a-form
        auto-label-width
        :model="demand.info"
        ref="formRef"
        :rules="rules"
      >
        <a-form-item
          field="processId"
          label="请选择审核组:"
          required
          label-col-flex="100px"
        >
          <a-select
            style="width: 230px"
            v-model="demand.info.processId"
            placeholder="请选择"
          >
            <a-option
              v-for="item in flowProcess"
              :key="item.id"
              :value="item.id"
              >{{ item.name }}</a-option
            >
          </a-select>
        </a-form-item>
      </a-form></div
    >
  </a-modal>
</template>

<script lang="ts" setup>
  import { ref, reactive, onMounted } from 'vue';
  import {
    getDemandFormStatusOn,
    postDemandForm,
  } from '@/api/order-management/client-management/demand/demand';
  import { GetPersonnelinformation } from '@/api/home/System settings/personal-information/index';
  import { useRouter } from 'vue-router';
  import { getFlowProcessAll } from '@/api/order-management/client-order/index';

  const router = useRouter();
  const breadCrumb: string[] = ['需求管理', '客户需求', '录入需求'];
  const title: string = '录入需求';
  const layout = ref('vertical');
  type Tlayout = 'inline' | 'horizontal' | 'vertical' | undefined;
  const fakeValue = ref(['']);
  const formRef = ref();

  // 获取审核组数据
  const flowProcess = ref([]);
  const getFlowProcessData = async () => {
    const res = await getFlowProcessAll({ page: 1, size: 99999 });
    flowProcess.value = res.content;
  };
  getFlowProcessData();

  let userData = JSON.parse(sessionStorage.getItem('loginInfo') as any);

  const visible = ref(false);
  const demand = reactive<any>({
    info: {
      flow: null, //
      number: '', //编号
      clientCompanyId: null, //客户
      userStaffId: null, //业务经理
      contractId: null, //关联合同id
      customerId: '', //客户联系人id
      extend: '', //扩展
      orderTime: null, //订单时间
      invoiceInformation: '', //收款方式
      payMode: null, //付款方式
      remark: null, //备注
      invoiceId: null,
      orderTemplateId: null, //模板ID
      product: [], //产品详情
      delivery: [], //产品详情
      state: 0,
      collectionAccountId: null,
      file: [],
      processId: null,
    },
  });

  const rules = reactive({
    processId: [{ required: true, message: '请选择审核组' }],
  });

  //   储存客户列表数据
  const clientList: any = reactive({
    list: [],
  });
  interface DemandFormType {
    info: {
      id: number;
      flowId: number;
      design: {
        form: any[];
      };
    };
  }
  const demandForm = reactive<DemandFormType>({
    info: { id: 0, flowId: 0, design: { form: [] } },
  });
  const getByTemplateStatusOn = async () => {
    let res = await getDemandFormStatusOn({ type: 1 });
    demandForm.info = res;
    demandForm.info.design.form.sort((a: any, b: any) => a.sort - b.sort);
    demandForm.info.design.form.forEach((item: any) => {
      item.props = JSON.parse(item.props);
      if (item.values !== '') {
        item.values = JSON.parse(item.values);
        if (item.values[0] === '') {
          item.values = [];
        }
      }
      if (item.code === 'TABLE') {
        item.props = {
          data: [],
          totalPrice: 0,
        };
      }
      if (item.code === 'DELIVERY_REQUIREMENTS_BC') {
        item.props = {
          data: [],
        };
      }
      if (item.code === 'BUSINESS_MANAGER') {
        item.values = [userData.id];
      }
    });
    demand.info.orderTemplateId = demandForm.info.id;
    demand.info.flow = demandForm.info.flowId;
  };

  const keys = Object.keys(demand.info);
  let refForm = ref();
  const addDemand = async () => {
    if (!(await refForm.value.validate())) visible.value = true;
  };

  const handleOk = async () => {
    formRef.value.validate(async (res) => {
      if (!res) {
        demandForm.info.design.form.forEach((item) => {
          if (item.code === 'TABLE') {
            demand.info.product = item.props.data;
          }
          if (item.code === 'FILE') {
            demand.info.file = item.props.data;
          }
          if (item.code === 'DELIVERY_REQUIREMENTS_BC') {
            demand.info.delivery = item.props.data;
          }
          if (item.fieldName && keys.includes(item.fieldName)) {
            demand.info[item.fieldName] = item.values[0];
          }
        });

        demand.info.extend = JSON.stringify(demandForm.info.design.form);
        demand.info.state = 1;
        demand.info.customerId = Number(demand.info.customerId);
        demand.info.orderTime = new Date(demand.info.orderTime).toJSON();
        demand.info.delivery.forEach((item: any) => {
          item.items.map((element: any) => {
            element.deliveryTime = new Date(element.deliveryTime).toJSON();
            return element;
          });
        });
        await postDemandForm(demand.info);
        router.back();
      } else {
        visible.value = true;
      }
    });
  };
  onMounted(() => {
    // 如果是添加则获取状态开启的那个模板
    getByTemplateStatusOn();
    // 如果是编辑则获取对应的模板
  });
</script>

<style scoped lang="less">
  .demand-index {
    padding: 25px 140px;
    width: 95%;
    margin: 0 auto;
    .addClient {
      position: absolute;
      margin-left: 20px;
      margin-top: -15px;
    }
  }

  .success {
    position: absolute;
    right: 30px;
    background-color: #31c27c;
    color: #fff;
    border-radius: 100%;
    width: 50px;
    text-align: center;
  }

  .blacklist {
    position: absolute;
    right: 30px;
    background-color: red;
    color: #fff;
    margin-left: 20px;
    border-radius: 100%;
    width: 50px;
    text-align: center;
  }

  .title {
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .title-item {
    width: 95%;
    height: 60px;
    margin: auto;
    background-color: rgba(245, 247, 250);
    line-height: 60px;
    margin-top: 20px;
  }
  .box {
    padding-top: 10px;
    margin-top: 20px;
    border-top: 1px solid #e4e4e4;
    display: flex;
    justify-content: end;
    width: 100%;
  }

  .items {
    padding-top: 5px;
    display: flex;
    align-items: center;
    justify-content: center;
  }
</style>
